#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/mman.h>
#include<stdio.h>

typedef struct {
    size_t size;
    size_t offset;
    char data[100];
} pos;

// static pos position;

typedef struct _student{
    int id;
    char name[50];
}Student;


int fileSize(int fd){
    struct stat stat;
    int size = -1;
    if (fstat(fd, &stat) == -1) {
        return -1;
    } else {
        size = stat.st_size;
        return size;
    }
}

void* writeShareMem(int fd, int size){
    ftruncate(fd, 3*2048);
    //映射到内存
	pos* position = mmap(NULL,1024,PROT_READ | PROT_WRITE,MAP_SHARED, fd, 4*1024);
	if(position == MAP_FAILED){
		perror("mmap");
		return 1;
	}

    printf("mmap success\n");
    printf("size:%d\n",size);

    position->offset = size;
    position->size = size;

	//写文件
	// memcpy(position.data,"abc123\n",7);
    // position.offset += 7;
    sprintf(position->data+position->offset, "abc123\n");
    position->offset += 7;
    position->size += 7;

    sprintf(position->data+position->offset, "mnk123\n");
    position->offset += 7;
    position->size += 7;

    sprintf(position->data+position->offset, "123456\n");
    position->offset += 7;
    position->size += 7;

    // ftruncate(fd, 2048);
    printf("size:%d\n",position->size);

    return position;
}

void freeShareMem(void* ptr, int fd){
    //断开映射
	munmap(ptr,1024);
    //关闭文件
	close(fd);
}

int main(){
	
	int fd=-1;
	void *addr=NULL;
    int size = 0;

	//打开文件
	fd=open("test.txt",O_RDWR, 0666);
	if(-1==fd){
		perror("open");
		return 1;
	}

    // ftruncate(fd, 1024);
    // int length = sizeof(Student);
    size = fileSize(fd);
    printf("file size=%d\n",size);
    // close(fd);
    void* ptr = writeShareMem(fd, size);
    freeShareMem(ptr, fd);

    // ftruncate(fd, 2048);
    // printf("size:%d\n",position->size);

	return 0;

}